﻿using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace I_Produce.Infrastructure
{
    public class BaseRepository<T> : IRepository<T> where T : class, new()
    {
        private readonly EFCoreDbContext _dbContext;

        public BaseRepository(EFCoreDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<int> AddAsync(T entity)
        {
            await _dbContext.AddAsync(entity);
            return await _dbContext.SaveChangesAsync();
        }

        public async Task<IQueryable<T>> All()
        {
            return await Task.FromResult(_dbContext.Set<T>().AsQueryable());
        }

        public async Task<int> BatchDeleteAsync(List<T> roleInfos)
        {
            _dbContext.RemoveRange(roleInfos);
            return await _dbContext.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(T entity)
        {
            _dbContext.Remove(entity);
            return await _dbContext.SaveChangesAsync();
        }

        public async Task<List<T>> GetAllAsync()
        {
            return await _dbContext.Set<T>().ToListAsync();
        }

        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            return await _dbContext.Set<T>().Where(expre).ToListAsync();
        }

        public async Task<T> GetByFuncAsync(Expression<Func<T, bool>> expre)
        {
            return await _dbContext.Set<T>().FirstOrDefaultAsync(expre);
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await _dbContext.Set<T>().FindAsync(id);
        }
        public async Task<int> UpdateAsync(T entity)
        {
            _dbContext.Update(entity);
            return await _dbContext.SaveChangesAsync();
        }

        public async Task<int> UpdateRangeAsync(List<T> values)
        {
            _dbContext.UpdateRange(values);
            return await _dbContext.SaveChangesAsync();
        }
    }
}
